package com.luojing.myThread.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

/**
 * @author luojing
 * @create 2018/09/01 上午9:38
 **/
public class ForkJoinTaskDemo {

  public static void main(String[] args) throws ExecutionException, InterruptedException {
    ForkJoinPool forkJoinPool = new ForkJoinPool();
    CountTask countTask1 = new CountTask(1,20);
    Future<Integer> future1 = forkJoinPool.submit(countTask1);
    System.out.println(future1.get());
  }


}

class CountTask extends RecursiveTask<Integer>{
  private static int splitSize = 2;
  private int start,end;

  public CountTask(int start, int end) {
    this.start = start;
    this.end = end;
  }


  @Override
  protected Integer compute() {
    int sum = 0;
    boolean canComplete =  (end - start) <= splitSize;
    if(canComplete){
      for(int i = start;i <= end; i++){
        sum = sum + i;
      }
    }else{
      System.out.println("Thread:" + Thread.currentThread().getName());
      int middle = (start + end) / 2;
      CountTask firstTask = new CountTask(start,middle);
      CountTask endTask = new CountTask(middle+1,end);
      firstTask.fork();
      endTask.fork();
      int firstResult = firstTask.join();
      int endResult = endTask.join();
      try {
        Thread.sleep(5000L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      sum = firstResult + endResult;
    }
    return sum;
  }
}